"""
@name : 12-14 Linux用户管理类
@author : hj
@projectname: CJH
"""
# -*- coding:utf-8 -*-
import subprocess


class Base:
    # 添加用户
    def adduser(self, username, userpasswd):
        subprocess.Popen(f'useradd {username} -p {userpasswd} && echo "{username}用户创建成功" || echo  "{username}用户创建失败"',
                         shell=True)


class A(Base):
    # 能够查看、修改uid和gid、shell等信息
    def checkuser(self, username):
        subprocess.Popen(f"cut -d ':' -f 1,3,4,7 /etc/passwd|grep {username}", shell=True)

    def modifyuser(self, username, uid, gid, shell):
        subprocess.Popen(f'usermod -u {uid} -g {gid} -s {shell} {username} && echo "修改成功" ||echo "修改失败"',
                         shell=True)


class B:
    # 1.能删除用户
    def deluser(self, username):
        subprocess.Popen(f'userdel  -r {username} && echo "用户删除成功" ||echo "用户删除失败"', shell=True)

    # 2.能删除组
    def delgroup(self, groupname):
        subprocess.Popen(f'groupdel  {groupname} && echo "组删除成功" ||echo "组删除失败"', shell=True)


class C(A, B):
    gid = []

    # 可以单独新建组
    def addgroup(self, groupname,gid):
        subprocess.Popen(f'groupadd  -g {gid} {groupname} && echo "组新建成功" ||echo "组新建失败"',
                         shell=True)
        C.gid.append(gid)

    # 可以将某个用户的gid修改为新建的 组的gid
    def modifygid(self, username, gid):
        if gid in C.gid:
            subprocess.Popen(f'usermod  -g {gid} {username} && echo "gid修改成功" ||echo "gid修改失败"', shell=True)
        else:
            print(f"用户指定的gid {gid}不在新建的组的gid内，无法修改")


class MyException(Exception):
    def __str__(self):
        return "自定义异常"


while True:
    print("Linux用户管理系统".center(80, "*"))
    print("1.添加用户\t2.查看用户信息\t3.修改用户信息\t4.删除用户\t5.删除组\t6.新建组\t7.修改用户gid")
    choice = input("请选择：")
    if choice == '1':
        c = C()
        username = input("请输入要添加的用户：")
        userpasswd = input("请设置密码：")
        c.adduser(username, userpasswd)
    elif choice == '2':
        c = C()
        username = input("请输入要查看的用户：")
        c.checkuser(username)
    elif choice == '3':
        c = C()
        name, uid, gid, shell = input("请输入用户名，修改后的uid、gid和shell，空格隔开").split()
        c.modifyuser(name, uid, gid, shell)
    elif choice == '4':
        c = C()
        username = input("请输入要删除的用户：")
        c.deluser(username)
    elif choice == '5':
        c = C()
        groupname = input("请输入要删除的组：")
        c.delgroup(groupname)
    elif choice == '6':
        c = C()
        groupname = input("请输入要新建的组名：")
        gid = input("请输入gid：")
        c.addgroup(groupname,gid)
    elif choice == '7':
        c = C()
        username = input("请输入用户名：")
        gid = input("请输入gid")
        c.modifygid(username, gid)
    else:
        print("请输入正确的选择")
